//
//  CIDetectorViewController.swift
//  CPT3
//
//  Created by onemade on 12/8/15.
//  Copyright © 2015 CNPC. All rights reserved.
//

import UIKit

class CIDetectorViewController: UIViewController {
    @IBOutlet weak var inputImageView: UIImageView!
    @IBOutlet weak var outputImageView: UIImageView!
    
    @IBAction func detect(sender: UIButton) {
        let context = CIContext(options: nil)
        let imageInput = self.inputImageView.image
        let image = CIImage(CGImage: imageInput!.CGImage!)
        let param = [CIDetectorAccuracyHigh: CIDetectorAccuracyHigh]
        let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: context, options: param)
        let detectResult = faceDetector.featuresInImage(image) as! [CIFaceFeature]
        let resultView = UIView(frame: self.inputImageView.frame)
        self.view.addSubview(resultView)
        
        for faceFeature in detectResult{
            let faceView = UIView(frame: faceFeature.bounds)
            faceView.layer.borderWidth = 1
            faceView.layer.borderColor = UIColor.orangeColor().CGColor
            resultView.addSubview(faceView)
            
            if faceFeature.hasLeftEyePosition{
                let leftEyeView = UIView(frame: CGRectMake(0,0,5,5))
                leftEyeView.center = faceFeature.leftEyePosition
                leftEyeView.layer.borderColor = UIColor.redColor().CGColor
                leftEyeView.layer.borderWidth = 1
                resultView.addSubview(leftEyeView)
            }
            if faceFeature.hasRightEyePosition{
                let rightEyeView = UIView(frame: CGRectMake(0,0,5,5))
                rightEyeView.center = faceFeature.rightEyePosition
                rightEyeView.layer.borderColor = UIColor.redColor().CGColor
                rightEyeView.layer.borderWidth = 1
                resultView.addSubview(rightEyeView)
            }
            if faceFeature.hasMouthPosition{
                let mouthView = UIView(frame: CGRectMake(0,0,5,5))
                mouthView.center = faceFeature.mouthPosition
                mouthView.layer.borderColor = UIColor.redColor().CGColor
                mouthView.layer.borderWidth = 1
                resultView.addSubview(mouthView)
            }
        }
//        var transform = CGAffineTransformMakeTranslation(50, 0)
//        transform = CGAffineTransformScale(transform, 1, -1)
//        resultView.transform = transform
        resultView.transform = CGAffineTransformMakeScale(1, -1)
        if detectResult.count > 0{
            let faceImage = image.imageByCroppingToRect(detectResult[0].bounds)
            let face = UIImage(CGImage: context.createCGImage(faceImage, fromRect: faceImage.extent))
            self.outputImageView.image = face
        }
    }
}
